<template>
  <el-dialog
    v-model="visible"
    :title="title" :close-on-press-escape="false" :close-on-click-modal="false"
    :show-close="false"
    :lock-scroll="false">
    <el-form ref="formRef" :model="roleInfo" :rules="roleRules">
      <el-form-item label="用户名称" prop="roleName">
        <el-input v-model="roleInfo.roleName" placeholder="请输入角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input type="textarea" maxlength="50" show-word-limit v-model="roleInfo.description" placeholder="请输入角色描述"
                  clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel">关闭</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { onMounted, ref, toRefs } from 'vue'
import { propsConst } from '@/utils/propsConstant'
import { post } from '@/utils/httpRequest'
import { addRoleUrl, queryRoleByIdUrl, updateRoleByIdUrl } from '@/api/api'
import { ElMessage } from 'element-plus'
import { roleRules } from '@/views/roleManage/components/data'

export default {
  name: 'roleInfo',
  setup (props, { emit }) {
    const {
      type,
      roleId
    } = toRefs(props)
    const cancel = () => {
      emit('update:visible', false)
    }
    const formRef = ref(null)
    const add = async () => {
      const result = await post(addRoleUrl, roleInfo.value)
      if (result.code === 200) {
        ElMessage.success('新增角色成功')
        cancel()
        emit('save')
      }
    }
    const update = async () => {
      const result = await post(updateRoleByIdUrl, roleInfo.value)
      if (result.code === 200) {
        ElMessage.success('编辑角色成功')
        cancel()
        emit('save')
      }
    }
    const save = async () => {
      formRef.value.validate().then(() => {
        if (type.value === 0) {
          add()
        } else if (type.value === 1) {
          update()
        }
      })
    }

    const roleInfo = ref({
      roleName: null,
      description: null
    })
    onMounted(async () => {
      if (type.value === 1) {
        const result = await post(queryRoleByIdUrl, { id: roleId.value })
        if (result.code === 200) {
          roleInfo.value = result.data
        }
      }
    })
    return {
      save,
      cancel,
      formRef,
      roleRules,
      roleInfo
    }
  },
  props: Object.assign(propsConst, {
    roleId: {
      type: String,
      default: 0
    }
  })
}
</script>

<style scoped>

</style>
